package net.adetech.crj.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import net.adetech.crj.entity.tb.CommanArgs;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ApiUtils {
    @Value("${api_service.url}")
    private String apiServiceUrl;

    private static final String FUNCCODE_SQ_MAKEBARCODE = "sq_makeBarcode";


    public JSONObject call(String funccode,String args)
    {
        String responseString = "{}";
        try {
            List<NameValuePair> paramList = new ArrayList<NameValuePair>();
            paramList.add(new BasicNameValuePair("funccode",funccode));
            paramList.add(new BasicNameValuePair("args",args));
            HttpEntity reqEntity = new UrlEncodedFormEntity(paramList,"utf-8");
            HttpClient client = HttpClients.createDefault();
            HttpPost request = new HttpPost(apiServiceUrl);
            request.setEntity(reqEntity);
            //request.setHeader("Authorization","APPCODE f77530e7d1324c3bbd47c819aa33711c");
            HttpResponse response = client.execute(request);
            responseString = EntityUtils.toString(response.getEntity());

        }catch (Exception e)
        {
            e.printStackTrace();
        }

        JSONObject responseObject = JSON.parseObject(responseString);

        return responseObject;
    }


    public String getYwbh(){
        String ywbh = null;
//        ywbh = "372018041800001";

        String args = "{prefix:'37'}";
        JSONObject response = this.call(FUNCCODE_SQ_MAKEBARCODE,args);
        if (response.getInteger("success")==1)
        {
            ywbh = response.getJSONObject("data").getString("barcode");
        }

        return ywbh;
    }

    public JSONObject queryBySfzh(String funccode,String sfzh)
    {
        CommanArgs commanArgs = new CommanArgs();
        commanArgs.setSfzh(sfzh);
        String args = JSON.toJSONString(commanArgs);
        JSONObject result = this.call(funccode,args);
        return  result;
    }


    public JSONObject call(String funccode,JSONObject args)
    {
        return call(funccode,args.toJSONString());
    }
}
